#coding:utf-8
import re
import json
import random
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from lovewith.album.views.modules.album import AlbumApi
from lovewith.analytics.views.modules.analyticsapi import ShopAnalyticsApi
from lovewith.api.qiniu import Qiniu
from lovewith.promote.views.modules.goods_tag import GoodsAttachTagApi
from lovewith.share.views.modules.attach_tag import AttachTagApi
from lovewith.supplier.views.modules.supplierapi import SupplierApi
from lovewith.utils.mtcache import MtCache
from lovewith.api.t import WbControlCenter
from lovewith.settings import FILE_UPLOAD_PATH
from lovewith.share.views.modules.share import ShareApi
from lovewith.share.views.modules.attach import AttachApi
from lovewith.share.views.modules.comment import ShareCommentApi
from lovewith.share.views.modules.attach_like import AttachLikeApi
from lovewith.share.views.modules.attach_flag import AttachFlagApi
from lovewith.website.views.modules.category import CategoryApi
from lovewith.website.views.modules.color import ColorApi
from lovewith.website.views.modules.province import ProvinceApi
from lovewith.website.views.modules.role import AttachRoleApi


#get like number
def get_like_num(request):
    total = 0
    image_id = request.GET.get('image_id' or None)
    share_id = request.GET.get('share_id' or None)
    item_data = []
    user_like = False

    if image_id:
        image_data = AttachApi.check_data(image_id)
        if image_data:
            total = AttachLikeApi.get_total_by_image(image_data)
            if request.user.is_authenticated():
                user_like = AttachLikeApi.get_total_by_image(image_data.id, request.user.id)
    if share_id:
        all_image_data = AttachApi.get_by_share(share_id)
        for img in all_image_data:
            is_user_like = False
            like_num = AttachLikeApi.get_total_by_image(img.id)

            if request.user.is_authenticated():
                user_like = AttachLikeApi.get_total_by_image(img.id, request.user.id)
                if user_like > 0:
                    is_user_like = True

            item_data.append({
                'image_id': img.id,
                'is_like': is_user_like
            })
            total += like_num

    result = {'total': total, 'item_data': item_data, 'user_like': user_like}

    return HttpResponse(json.dumps(result))


#add like
@login_required
def add_like(request):
    state = False
    share_data = None
    wb_url = None
    wb_image = None
    image_id = request.GET.get('image_id' or None)
    share_id = request.GET.get('share_id' or None)
    tag = request.GET.get('tag' or None)
    wb_like_text = ['不错，可以借鉴下哦~',
                    '哇塞，有创意！',
                    '灰常赞啊~',
                    '给力，支持你下~',
                    '楼主，给你来点赞了哦~',
                    '牛！很牛！非常牛！总之牛死了~~',
                    '还不错呦！',
                    '楼主，很不错哦，支持你!!',
                    '飘过~',
                    '顶~永远支持你哦~']
    wb_at_origin_user = []

    if share_id:
        #like帖子
        share_data = ShareApi.check_data(share_id)
        combo_path = share_data.combo_path
        image_data = AttachApi.get_by_share(share_id)
        if image_data:
            AttachLikeApi().add_to_image(image_data, request.user)
            #增加一条评论
            ShareCommentApi.add(share_data, random.choice(wb_like_text), request.user)

            wb_url = 'http://www.lovewith.me/share/detail/all/%s' % share_data.id

            #没有大图
            if combo_path == '':
                combo_data = ShareApi().get_combo_image(share_id)
                if combo_data:
                    wb_image = combo_data
            else:
                if combo_path:
                    if combo_path.find('http') < 0:
                        wb_image = '%sshare/%s' % (FILE_UPLOAD_PATH, combo_path)
                    else:
                        wb_image = combo_path
            state = True

    if image_id:
        #like图片
        image_data = AttachApi.check_data(int(image_id))
        if image_data:
            state = True
            AttachLikeApi().add_to_image([image_data], request.user)
            share_data = image_data.share_post
            #增加一条评论
            ShareCommentApi.add(share_data, random.choice(wb_like_text), request.user)

            wb_url = 'http://www.lovewith.me/share/detail/%s/?mid=%s' % (share_data.id, image_data.id)

            if image_data.path.find('http') < 0:
                wb_image = '%sshare/%s' % (FILE_UPLOAD_PATH, image_data.path)
            else:
                wb_image = '%s!650' % image_data.path

    #获取所有打标的用户名
    origin_user = ShareApi.get_origin(share_data.id)
    for u in origin_user:
        wb_at_origin_user.append(u.get('user'))

    if len(wb_at_origin_user) > 0:
        wb_at_origin_user = ' @%s' % ' @'.join(wb_at_origin_user)
    else:
        wb_at_origin_user = ''

    if state and wb_url and wb_image:
        #成功后判断是否需要同步到微博
        like_total = AttachApi().get_total_like(share_data.id, request.user.id)

        if not tag:
            content = '我喜欢了【%s】[得意地笑] %s %s @_@' % (share_data.title, wb_url, wb_at_origin_user)
        else:
            content = '%s好赞[偷乐]【%s】 %s %s @_@' % (tag, share_data.title, wb_url, wb_at_origin_user)

        WbControlCenter(request.user, 'like').send_media(content, wb_image, at_user_id=share_data.user.id)

        result = {'error': False, 'like': like_total}
    else:
        result = {'error': True}

    return HttpResponse(json.dumps(result))


#remove like
@login_required
def remove_like(request):
    result = {'error': True}
    image_id = request.GET.get('image_id')
    share_id = request.GET.get('share_id')
    need_update = False

    if image_id:
        image_data = AttachApi.check_data(int(image_id))
        if image_data:
            AttachLikeApi.remove_as_image(image_data, request.user)
            need_update = True
            result = {'error': False}

    if share_id:
        share_data = ShareApi.check_data(share_id)
        if share_data:
            image_data = AttachApi.get_by_share(share_id)
            for img in image_data:
                AttachLikeApi.remove_as_image(img, request.user)

            need_update = True
            result = {'error': False}
    #清空缓存
    if need_update:
        for i in range(10):
            MtCache('user_like').delete(user_id=request.user.id, page=i + 1)

    return HttpResponse(json.dumps(result))


#查询结果缓存10分钟
#@cache_page(10 * 60)
def get_share_page_data(request):
    page_no = int(request.GET.get('page', 1))
    cate_id = request.GET.get('cate_id')
    user_id = request.GET.get('uid')
    user_type = request.GET.get('utype')
    tag = request.GET.get('tag', None)
    key = request.GET.get('keyword', None)
    color = request.GET.get('color', None)
    content_type = request.GET.get('type', 'selected')

    share_data = None

    if tag:
        share_data = ShareApi().get_by_tag(tag, page_no)
    if color:
        share_data = ShareApi.get_by_color(color, page_no)
    if key:
        share_data = ShareApi.get_by_title(key, page_no)
    if cate_id:
        share_data = ShareApi.get_by_cate(int(cate_id), page_no, content_type=content_type)
    if user_id:
        if user_type == 'post':
            share_data = ShareApi().get_post_by_user(int(user_id), page_no)

        if user_type == 'like':
            share_data = ShareApi.get_like_by_user(int(user_id), page_no)

    the_share_data = []
    if share_data and share_data.has_key('share'):
        the_share_data = share_data.get('share')

    result = {
        'page': page_no,
        'data': the_share_data
    }

    return HttpResponse(json.dumps(result))


#商品异步接口
def get_goods_page_data(request):
    page_no = int(request.GET.get('page', 1))
    tag = request.GET.get('tag')
    cate_id = request.GET.get('cate')

    goods_data = {}

    if tag:
        if tag == 'all':
            goods_data = AttachFlagApi.get_by_tag(tag='all', page_no=page_no)
        else:
            goods_data = AttachFlagApi.get_by_tag(tag=tag, page_no=page_no)
    if cate_id:
        goods_data = AttachFlagApi.get_by_cate(cate_id=cate_id, page_no=int(page_no))

    result = {
        'page': page_no,
        'data': goods_data.get('goods')
    }

    return HttpResponse(json.dumps(result))


#获取评论
def get_comment(request):
    share_id = request.GET.get('sid') or 0
    page_no = int(request.GET.get('page') or 1)

    comment_data = ShareCommentApi().get_by_page(share_id=share_id, page_no=page_no)

    result = {
        'page_no': comment_data['page_no'],
        'total': comment_data['total'],
        'total_page': comment_data['total_page'],
        'data': comment_data['data']
    }

    return HttpResponse(json.dumps(result))


#添加评论
@login_required
def add_comment(request):
    share_id = request.POST.get('sid')
    content = request.POST.get('content')
    sync_wb = request.POST.get('syncWb')
    sync_qq = request.POST.get('syncQq')
    at_wb_user = ''
    result = {'error': True}
    wb_at_orgin_user = []

    if sync_wb == '1':
        sync_wb = True
    else:
        sync_wb = False

    if sync_qq == '1':
        sync_qq = True
    else:
        sync_qq = False

    share_data = ShareApi.check_data(share_id)
    if share_data:
        comment_id = ShareCommentApi.add(share_data, content, request.user)
        result = {'error': False, 'msg': comment_id}

        orgin_user = ShareApi.get_origin(share_data.id)
        for u in orgin_user:
            wb_at_orgin_user.append(u.get('user'))

        if len(wb_at_orgin_user) > 0:
            at_wb_user = ' @%s' % ' @'.join(wb_at_orgin_user)

    text = '我刚刚在婚礼时光发表了评论“ %s” %s @_@ http://www.lovewith.me/share/detail/all/%s' \
           % (content[0:80], at_wb_user, share_id)
    WbControlCenter(request.user, 'comment').send_text(
        text,
        at_user_id=share_data.user_id,
        sync_wb=sync_wb,
        sync_qq=sync_qq
    )

    return HttpResponse(json.dumps(result))


#删除评论
@login_required
def delete_comment(request):
    comment_id = int(request.GET.get('mid') or -1)
    comment_data = ShareCommentApi.check_data(comment_id)
    result = {'error': True}

    if comment_data:
        if request.user.is_admin or request.user.id == comment_data.user_id:
            comment_data.delete()
            result = {'error': False}

    return HttpResponse(json.dumps(result))


#推荐&&取消推荐
@login_required
def update_recommend(request):
    share_id = request.GET.get('sid')
    result = {'error': True}

    if share_id and request.user.is_admin:
        share_data = ShareApi.check_data(share_id)
        if share_data:
            if share_data.is_recommend == 0:
                share_data.is_recommend = 1
                share_data.save()
            else:
                share_data.is_recommend = 0
                share_data.save()

            result = {'error': False}

    return HttpResponse(json.dumps(result))


#用于标注的预定义商品标签
def get_maker_goods_tags(request):
    goods_tag = GoodsAttachTagApi.get_all()
    return HttpResponse(json.dumps({'goods_tag': goods_tag}))


#用于标注的预定义用户角色
def get_maker_user_role(request):
    role_data = AttachRoleApi.get_all()
    return HttpResponse(json.dumps({'role_data': role_data, }))


#删除分享
@login_required
def delete(request):
    user = request.user
    del_type = request.GET.get('type')
    type_id = request.GET.get('id')
    result = {'error': True}

    if del_type == 'share':
        share_data = ShareApi.check_data(type_id)
        if share_data:
            if user.id == share_data.user.id or user.is_admin:
                ShareApi.delete(share_data)
                result = {'error': False}

                #清空缓存
                #for i in range(15):
                #    MtCache('user_post').delete(user_id=share_data.user.id, page=i+1)
                #    MtCache('user_like').delete(user_id=share_data.user.id, page=i+1)
                #    MtCache('user_post').delete(user_id=share_data.user.id, page=i+1)
                #    MtCache('cate_share').delete(cate_id=share_data.cate_id, page=i+1)

    if del_type == 'image':
        image_data = AttachApi.check_data(type_id)
        if image_data:
            if image_data.share_post.user.id == user.id or user.is_admin:
                AttachApi().delete(image_data.id)
                result = {'error': False}

    return HttpResponse(json.dumps(result))


#添加来源数据
@login_required
def add_origin_marker(request):
    share_id = request.POST.get('sid')
    role_id = request.POST.get('role')
    origin_user = request.POST.get('orginUser')

    result = {'error': True}

    if role_id and share_id:
        share_data = ShareApi.check_data(share_id)
        role_data = AttachRoleApi.check_data(int(role_id))

        if share_data and role_data:
            post_states = ShareApi.add_origin(share_data, origin_user, role_data, request.user)

            if post_states:
                result = {'error': False}

    return HttpResponse(json.dumps(result))


#添加淘宝客标注
@login_required
def add_goods_marker(request):
    image_id = request.POST.get('mid')
    position = request.POST.get('position')
    title = request.POST.get('title')
    tagname = request.POST.get('tagname')
    url = request.POST.get('detail_url')
    price = request.POST.get('price')

    result = {'error': True}

    image_data = AttachApi.check_data(image_id)
    if image_data:
        AttachFlagApi.add_goods(image_data, tagname, position, title, url, price, request.user)

        result = {'error': False}

    return HttpResponse(json.dumps(result))


#上传图片
def upload_image(request):
    attach = request.FILES.get('file', None)
    avatar_path = Qiniu('mt-temp').upload(attach)

    return HttpResponse(json.dumps(avatar_path))


#获取用户导航数据
def get_user_nav_data(request):
    uid = request.GET.get('uid')
    user_like_num = 0
    album_num = 0
    if uid:
        user_like_num = AttachLikeApi.get_total_by_user(uid)
        album_num = AlbumApi.get_album_count_by_user(uid)

    result = {
        'like': user_like_num,
        'album': album_num
    }

    return HttpResponse(json.dumps(result))


#新浪微博linkcard接口
def wb_link_card(request):
    url = request.GET.get('url')
    result = {}

    if url:
        match = re.findall(r'^http://www\.lovewith\.me/share/detail/all/(\d+)\D*.*', url)
        if match and match[0]:
            share_data = ShareApi.check_data(match[0])
            if share_data:
                share_cover_data = AttachApi.get_cover_attach(share_data.id)
                if share_cover_data:
                    cover_path = share_cover_data.get('cover').path
                    if cover_path.find('http') < 0:
                        cover_path = 'http://img.lovewith.me/upload/share/%s' % cover_path
                    else:
                        cover_path = '%s!650' % cover_path

                    result = {
                        "object_type": "webpage",
                        "display_name": share_data.title,
                        "links": {
                            "url": url,
                            "display_name": "查看全文"
                        },
                        "author": {
                            "url": "http://www.lovewith.me/u/%s/" % share_data.user_id,
                            "object_type": "person",
                            "display_name": share_data.user.username
                        },
                        "url": url,
                        "image": {
                            "url": cover_path
                        },
                        "full_image": {
                            "url": cover_path
                        },
                        "create_at": share_data.post_date.strftime('%Y年%m月%d日'),
                        "summary": re.compile(r'<[^>]+>', re.S).sub('', share_data.content)
                    }

    return HttpResponse(json.dumps(result))


#获取预设tag
@login_required
def get_preset_tag(request):
    result = []
    tag = request.GET.get('tag')
    if tag and not tag == '':
        result = AttachTagApi.get_preset(tag)

    return HttpResponse(json.dumps(result))


#类目&&颜色数据
def get_cate_and_color_data(request):
    result = {
        'cates': CategoryApi.get_all(),
        'colors': ColorApi.get_all(),
    }

    return HttpResponse(json.dumps(result))


#获取图片服务类型
@login_required
def get_image_service_type(request):
    result = {}
    image_id = request.GET.get('mid')

    if image_id:
        selected_service_type = []
        attach_service_type = AttachApi.get_service_type(int(image_id))
        for img in attach_service_type:
            selected_service_type.append(img.service_id)

        all_service_data = SupplierApi.get_service_cate()

        result = {
            'select': selected_service_type,
            'all': all_service_data
        }

    return HttpResponse(json.dumps(result))


@login_required
def update_attach_service_type(request):
    image_id = request.POST.get('mid')
    service_type = request.POST.getlist('service')

    if request.user.is_admin and image_id:
        image_data = AttachApi.check_data(image_id=int(image_id))
        if image_data:
            attach_service_type = AttachApi.get_service_type(int(image_id))

            #删除原来的数据
            attach_service_type.delete()

            #验证服务类目的合法性
            validated_service_data = []
            for service_id in service_type:
                service_data = SupplierApi.check_service_cate(int(service_id))
                if service_data:
                    validated_service_data.append(service_data)

            if validated_service_data:
                AttachApi.add_service_type(validated_service_data, image_data)

    return HttpResponse(json.dumps({}))


#获取图片附加数据
def get_attach_ext_data(request):
    city_name = request.GET.get('city')
    image_id = request.GET.get('mid')
    result = {
        'supplier': []
    }

    if city_name and image_id:
        recommand_supplier_data = []

        image_data = ShareApi.get_ext_data(int(image_id))
        if image_data:
            service_type_id = []
            service_type_data = AttachApi.get_service_type(int(image_id))
            city_data = ProvinceApi.check_by_name(city_name=city_name)

            result['attach'] = image_data

            if service_type_data and city_data:
                for cid in service_type_data:
                    service_type_id.append(cid.service.id)

            if len(service_type_id) > 0:
                supplier_ids = SupplierApi.get_by_image(service_type_id, city_data.id)
                for supplier in supplier_ids:
                    supplier_data = SupplierApi.check_data(supplier_id=supplier['id'])
                    recommand_supplier_data.append({
                        'uid': supplier_data.user_id,
                        'username': supplier_data.company,
                        'avatar': supplier_data.user.avatar
                    })

                result['supplier'] = recommand_supplier_data

    return HttpResponse(json.dumps(result))


#记录帖子pv
def add_share_analytics_data(request):
    share_id = request.GET.get('sid')
    if share_id:
        share_data = ShareApi.check_data(int(share_id))
        if share_data:
            share_data.views += 1
            share_data.save()

            #由服务商提供的作品，统计数据+1
            if share_data.user.group_id == 3:
                supplier_data = SupplierApi.check_data(user_id=share_data.user_id)
                if supplier_data:
                    ShopAnalyticsApi.increase(supplier_data)

    return HttpResponse(json.dumps({}))


#保存采集图片到cdn
@login_required
def save_collect_image(request):
    image_url = request.GET.get('url')
    if image_url:
        image_tmp_url = Qiniu('mt-temp').save_remote(image_url, 'mt-temp')
        if image_tmp_url:
            return HttpResponse(json.dumps({'error': False, 'image': image_tmp_url}))

    return HttpResponse(json.dumps({'error': True}))